<?php

//TODO: Skapa en db config som skickas in till konstruktorn.
class Database
{
	private $databaseName = "";
	private $mysqli = null;

	// gör så den ska kunna anasluta 
	public function Connect(DBConfig $config) {
		$this->mysqli = new \mysqli($config->m_host, 
							 $config->m_user, 
							 $config->m_pass, 
							 $config->m_db);

		
		if ($this->mysqli->connect_error) {
		    throw new \Exception($this->mysqli->connect_error);
		}
		
		$this->mysqli->set_charset("utf8");
		
		return true;
	}
	
	public function SelectOne($sqlQuery) {
		
		$stmt = $this->mysqli->prepare($sqlQuery);
		
		if ($stmt === FALSE) {
			throw new \Exception($this->mysqli->error);
		}
		
		if ($stmt->execute() == FALSE) {
			throw new \Exception($this->mysqli->error);
		}
		$ret = 0;
		
		if ($stmt->bind_result($ret) == FALSE) {
			throw new \Exception($this->mysqli->error);
		}
		
		$stmt->fetch();
		
		$stmt->close();
		
		
		return $ret;
	}
	
	public function Select($sqlQuery) {
		
		$stmt = $this->mysqli->prepare($sqlQuery);
		
		if ($stmt === FALSE) {
			throw new \Exception($this->mysqli->error);
		}
		
		if ($stmt->execute() == FALSE) {
			throw new \Exception($this->mysqli->error);
		}
		$ret = 0;
		
		return $stmt;
	}
	
	public function Prepare($sql) {
		$ret = $this->mysqli->prepare($sql);
		
		if ($ret == FALSE) {
			throw new \Exception($this->mysqli->error);
		}
		
		return $ret;
		
	}
	
	public function RunInsertQuery(\mysqli_stmt $stmt) {
			
			
		if ($stmt->execute() == FALSE) {
			throw new \Exception($this->mysqli->error);
		}
		
		$ret = $stmt->insert_id;
		
		$stmt->close();
		
		return $ret;
	}
	
	public function Close() {
		return $this->mysqli->close();
	}	
}